package mall.controller.admin;

import com.google.gson.Gson;
import mall.model.Result;
import mall.model.Type;
import mall.model.bo.*;
import mall.model.vo.GetGoodsInfoVO;
import mall.model.vo.NoReplyMsgVO;
import mall.model.vo.RepliedMsgVO;
import mall.model.vo.TypeGoodsVO;
import mall.service.GoodsService;
import mall.service.GoodsServiceImpl;
import mall.utils.FileUploadUtils;
import mall.utils.HttpUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/*
 *
 * @author Yonni
 * @version 1.8.0_201
 * @date 2020-05-28 20:52
 *
 * */
@WebServlet("/api/admin/goods/*")
public class GoodsServlet extends HttpServlet {
    private GoodsService goodsService = new GoodsServiceImpl();
    private Gson gson = new Gson();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/admin/goods/", "");
        if ("imgUpload".equals(action)) {
            imgUpload(request, response);
        } else if ("addGoods".equals(action)) {
            addGoods(request, response);
        } else if ("addType".equals(action)) {
            addType(request, response);
        } else if ("reply".equals(action)) {
            reply(request, response);
        } else if ("updateGoods".equals(action)) {
            updateGoods(request, response);
        } else if ("addSpec".equals(action)) {
            addSpec(request, response);
        }

    }

    /**
     * 添加商品规格
     * 1. 获取请求参数{goodsId: "562", specName: "规格3", stockNum: "3", unitPrice: "876"}
     * 2. 跟新数据库表相应数据
     * 3. 作出响应{"code":0,"data":{"goodsId":"562","specName":"规格3","stockNum":"3","unitPrice":"876"}}
     * */
    private void addSpec(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        AddSpecBO addSpecBO = gson.fromJson(requestBody, AddSpecBO.class);
        goodsService.addSpec(addSpecBO);
        response.getWriter().println(gson.toJson(Result.ok(addSpecBO)));
    }

    /**
     * 更新商品信息
     * 1. 获取请求参数{id: "1", name: "阿尔托莉雅·潘德拉贡", typeId: 1,…}
     * 2. 往数据库表跟新相应数据
     * 3. 作出响应{"code":0}
     * */
    private void updateGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        UpdateGoodsBO updateGoodsBO = gson.fromJson(requestBody, UpdateGoodsBO.class);
        goodsService.updateGoods(updateGoodsBO);
        response.getWriter().println(gson.toJson(Result.ok()));
    }

    /**
     * 回复留言
     * 1. 获取请求参数{id: 2, content: "亲，谢谢支持"}
     * 2. 跟新数据库表contents数据
     * 3. 作出响应{"code":0}
     * */
    private void reply(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        ReplyBO replyBO = gson.fromJson(requestBody, ReplyBO.class);
        goodsService.reply(replyBO);
        response.getWriter().println(gson.toJson(Result.ok()));
    }

    /**
     * 添加商品类别
     * 1. 获取post请求参数{name: ""}
     * 2. 将数据添加到数据库type表
     * 3. 作出响应{"code":0}
     * */
    private void addType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        AddTypeBO typeBO = gson.fromJson(requestBody, AddTypeBO.class);
        goodsService.addType(typeBO);
        response.getWriter().println(gson.toJson(Result.ok()));
    }

    /**
     * 点击保存，发送一个post请求，具体做了：
     * 将json字符串转化为json对象，然后取出里面的数据，然后将一部分数据保存到goods表，
     * 还有一部分关于规格的数据保存到规格表，规格表中应该有一个字段为goodsId。
     * 新增商品后会有一个id，这个商品的id应该拿着接下来保存到规格表的goodsId
     * */

    /*
    * 保存商品的业务逻辑：
    * 1. 获取请求体中的参数
    * 2. 处理业务逻辑
    * 3. 作出响应
    * */
    private void addGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        AddGoodsBO goodsBO = gson.fromJson(requestBody, AddGoodsBO.class);
        goodsService.addGoods(goodsBO);
        response.getWriter().println(gson.toJson(Result.ok()));
    }

    /**
     * 新增商品图片
     * commons-fileUpload
     * 1. 直接执行具体的业务逻辑，上传图片
     * 2. 响应——抓服务器上的响应报文{"code":0,"data":"/static/image/1590681047341iL5Ruu0Mnd-compress.jpg"}
     * */
    private void imgUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, Object> map = FileUploadUtils.parseRequest(request);
        String file = (String) map.get("file");
        /**
         * 这里需要注意:
         * 服务器上面的路径没有携带域名端口号，那么就表示图片从当前域名端口去取
         * 如果你的图片和页面不在一个域内，那么应当指明你文件所在的域
         * http://115.29.141.32:8085/static/image/1590681047341iL5Ruu0Mnd-compress.jpg
         * file 是从localhost:8085取的，而我们的图片在8084
         * 因此需要用全路径 http://localhost:8084
         * */
        String domain = (String) getServletContext().getAttribute("domain");
        response.getWriter().println(gson.toJson(Result.ok(domain + file)));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/admin/goods/", "");
        if ("getType".equals(action)) {
            getType(request, response);
        } else if ("getGoodsByType".equals(action)) {
            getGoodsByType(request, response);
        } else if ("getGoodsInfo".equals(action)) {
            getGoodsInfo(request, response);
        } else if ("deleteGoods".equals(action)) {
            deleteGoods(request, response);
        } else if ("noReplyMsg".equals(action)) {
            noReplyMsg(request, response);
        } else if ("repliedMsg".equals(action)) {
            repliedMsg(request, response);
        }
    }

    /**
     * 显示已回复的留言
     * 1. 数据库表获取数据
     * 2. 作出响应{"code":0,"data":[{},{}...]}
     * */
    private void repliedMsg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<RepliedMsgVO> repliedMsgVOS = goodsService.repliedMsg();
        response.getWriter().println(gson.toJson(Result.ok(repliedMsgVOS)));
    }

    /**
     * 显示未回复的留言
     * 1. 数据库表获取数据
     * 2. 作出响应{"code":0,"data":[{},{}...]}
     * */
    private void noReplyMsg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<NoReplyMsgVO> noReplyMsgVOS = goodsService.noReplyMsg();
        response.getWriter().println(gson.toJson(Result.ok(noReplyMsgVOS)));
    }

    /**
     * 删除商品
     * 1. 获取请求参数id
     * 2. 根据id，删除数据库表goods, spec相应数据
     * 3. 作出响应{"code":0}
     * */
    private void deleteGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        goodsService.deleteGoods(id);
        response.getWriter().println(gson.toJson(Result.ok()));
    }

    /**
     * 获取商品信息
     * 1. 获取get请求参数id
     * 2. 带着参数去数据库获取数据
     * 3. 作出响应 {"code": 0, "data": {"specs": [], "goods": {}}}
     * */
    private void getGoodsInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        //校验id
        try {
            Integer.parseInt(id);
        } catch (Exception e) {
            response.getWriter().println("参数格式错误");
        }
        GetGoodsInfoVO goodsInfoVO =  goodsService.getGoodsInfo(id);
        response.getWriter().println(gson.toJson(Result.ok(goodsInfoVO)));
    }

    /**
     * 获取某个分类下的商品信息
     * 1. 获取分类id
     * 2. 数据库查询
     * 3. 按照一定的数据结构返回
     * */
    private void getGoodsByType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String typeId = request.getParameter("typeId");
        //校验typeId
        try {
            Integer.parseInt(typeId);
        } catch (Exception e) {
            response.getWriter().println("参数格式错误");
        }
        List<TypeGoodsVO> goodsVOList = goodsService.getGoodsByType(typeId);
        response.getWriter().println(gson.toJson(Result.ok(goodsVOList)));
    }

    /**
     * 加载商品的所有分类
     * 1. 没有请求参数
     * */
    private void getType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Type> typeList = goodsService.getType();
        response.getWriter().println(gson.toJson(Result.ok(typeList)));
    }
}
